﻿using System;
using System.Linq;
using System.Text;

using Xc.DataAccess.Core.Extensions;

namespace Xc.DataAccess.Core.Services
{
    public class HexEncoding : Encoding
    {
        public override int GetByteCount(char[] chars, int index, int count)
        {
            return count;
        }

        public override int GetBytes(char[] chars, int charIndex, int charCount, byte[] bytes, int byteIndex)
        {
            return bytes.Length;
        }

        public override int GetCharCount(byte[] bytes, int index, int count)
        {
            return bytes.Count();
        }

        public override int GetChars(byte[] bytes, int byteIndex, int byteCount, char[] chars, int charIndex)
        {
            return chars.Length;
        }

        public override int GetMaxByteCount(int charCount)
        {
            return 1;
        }

        public override int GetMaxCharCount(int byteCount)
        {
            return 1;
        }
        public override string GetString(byte[] bytes)
        {
            return bytes.ToHex();
        }
        public override byte[] GetBytes(string s)
        {
            try
            {
                if (s.Length%2!=0)
                {
                    return Array.Empty<byte>();
                }
                return s.ToHex();
            }
            catch (Exception err)
            {
                throw new Exception($"无法编码:{s},可能长度不够或包含异常字符");
            }

        }
    }
}
